package ru.smc.hogwarts.servlets.professors;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.House;
import ru.smc.hogwarts.model.Person;

public class ProfessorsEdit extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String error = "";
	private String firstName = null;
	private String lastName = null;
	private String status = null;
	private int house = 0;
	private String pInfo = null;
	private HttpSession session;
       
    public ProfessorsEdit() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = 0;
		request.setAttribute("error", error);
		
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
		
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch(NumberFormatException e) {}
		
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		Person professor = em.find(Person.class, id);
		
		if (professor == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {		
			List<House> houses = em.createQuery("select h from House h").getResultList();
			request.setAttribute("houses", houses);
	
			if (error == "") {				
				request.setAttribute("firstName", professor.getFirstName());
				request.setAttribute("lastName", professor.getLastName());
				request.setAttribute("status", professor.getStatus());
				request.setAttribute("house", professor.getHouse().getId());
				request.setAttribute("pInfo", professor.getpInfo());
			} else if (error != "") {
				request.setAttribute("firstName", firstName);
				request.setAttribute("lastName", lastName);
				request.setAttribute("status", status);
				request.setAttribute("house", house);
				request.setAttribute("pInfo", pInfo);
			}
			
			request.setAttribute("id", id);
							
			error = "";
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/pages/professors/professorEdit.jsp");
			dispatcher.forward(request, response);
		}

		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		int id = 0;
		
		try {
			try {
				id = Integer.parseInt(request.getParameter("id"));
			} catch(NumberFormatException e) {}
			
			firstName = request.getParameter("firstName");
			if (firstName == "") error += "<span>П</span>оле \"Имя\" не должно быть пустым.<br>";
						
			lastName = request.getParameter("lastName");
			if (lastName == "") error += "<span>П</span>оле \"Фамилия\" не должно быть пустым.<br>";
			
			status = request.getParameter("status");
			if (status == "") 
				error += "<span>П</span>оле \"Статус\" не должно быть пустым.<br>";
			
			if (request.getParameter("house") == "") {
				error += "<span>П</span>оле \"Факультет\" не должно быть пустым.<br>";
			} else {
				house = Integer.parseInt(request.getParameter("house"));
			}
			
			pInfo = request.getParameter("pInfo");
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if (error == "") { 
			this.updateProfessor(id, firstName, lastName, status, house, pInfo);
			response.sendRedirect(request.getContextPath() + "/professors");
		} else if (error != "") {
			response.sendRedirect(request.getContextPath() + "/professors/edit?id="+id);
		}
	}
	
	public void updateProfessor(int editorId, String firstName, 
			String lastName, String status, int house, String pInfo) {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		Person professor = em.find(Person.class, editorId);
		House _house = em.find(House.class, house);
		
		professor.setFirstName(firstName);
		professor.setLastName(lastName);
		professor.setStatus(status);
		professor.setHouse(_house);
		professor.setpInfo(pInfo);
		em.getTransaction().commit();
		
		em.close();
	}

}
